<script lang="ts" setup>
import * as productApi from "@/api/train/product";
import SpuItem from "./components/spu-item.vue";
import { useRouter, useRoute } from "vue-router";
import { getOSSURL } from "@/utils/utils";

const spuList = ref<ListProductSpu[]>([]);

const props = defineProps({
  type: {
    type: String,
    required: true,
  },
});


// 加载列表
const params = ref({
  pageNo: 1,
  pageSize: 10,
  carType: props.type
});
const resetParams = () => {
  params.value.pageNo = 1;
  params.value.pageSize = 10;
  params.value.carType = '';
};

// 加载列表
const loadList = (concat: boolean = false) => {
  productApi
    .getAllNormalSpuPage(params.value)
    .then((res) => {
      const newSpuList = res.data.list;
      spuList.value = concat ? spuList.value.concat(newSpuList) : newSpuList;
      infinityValue.value = false;
      if (newSpuList.length < params.value.pageSize) {
        hasMore.value = false;
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

// 上拉加载
const infinityValue = ref(false);
const hasMore = ref(true);
const loadMore = () => {
  params.value.pageNo++;
  loadList(true);
};

// 下拉刷新
const refresh = ref(false);
const refreshFun = () => {
  resetParams();
  loadList();
  refresh.value = false;
};

// 初始化列表
loadList();

// 跳转到详情页
const router = useRouter();
const handleSpuItemClick = (spu: ListProductSpu) => {
  router.push(`/mall/${spu.id}`);
};

</script>

<template>
  <div class="h-full">

        <nut-infinite-loading v-model="infinityValue" :has-more="hasMore" @load-more="loadMore" load-more-txt="—— 没有更多了 ——">
          <!-- 列表 -->
          <nut-pull-refresh v-model="refresh" @refresh="refreshFun">
            <div v-if="spuList.length" class="flex flex-col gap-3 p-3">
              <SpuItem v-for="item in spuList" :key="item.id" :spu="item" @click="handleSpuItemClick(item)" />
            </div>
            <nut-empty v-else image="empty" description="暂无报名商品" />
          </nut-pull-refresh>
        </nut-infinite-loading>
  </div>
</template>
